package com.meirimoney.utilities;

import android.content.Context;
import android.content.SharedPreferences;

import com.meirimoney.sdk.models.AccessToken;

public class TokenManage
{
	private final static TokenManage instance = new TokenManage();

	/***
	 * 获取AccessToken
	 * 
	 * @return
	 */
	private String getKey()
	{
		return "user";
	}

	/**
	 * 获取当前的实例
	 */
	public static TokenManage getInstance()
	{
		return instance;
	}

	/***
	 * 从私有存储器中获取Token
	 * 
	 * @param context
	 *            当前上下文
	 * @return
	 */
	public AccessToken getAccessToken(Context context)
	{
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				this.getKey(), Context.MODE_PRIVATE);
		String token = sharedPreferences.getString("token", null);
		String secret = sharedPreferences.getString("secret", null);
		int integralBalance = sharedPreferences.getInt("integralBalance", 0);
		AccessToken at = null;
		if (token != null && secret != null)
		{
			at = new AccessToken();
			at.Token = token;
			at.Secret = secret;
			at.IntegralBalance = integralBalance;
		}
		return at;
	}

	/***
	 * 保存当前的Token进入私有存储器中
	 * 
	 * @param context
	 *            当前上下文
	 * @param accessToken
	 */
	public void saveAccessToken(Context context, AccessToken accessToken)
	{
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				this.getKey(), Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("token", accessToken.Token);
		editor.putString("secret", accessToken.Secret);
		editor.putInt("integralBalance", accessToken.IntegralBalance);
		editor.commit();
	}
}
